import { defineStore } from 'pinia'
import request from '@/utils/request'
import router from '@/router/index'

export const useUserStore = defineStore('user', {
  state: () => ({
    username: '',
    password: '',
    phone: '',
    gender: '',
    token: '',
    isLoading: false,
    error: null
  }),
  actions: {
    async login(userData) {
      this.isLoading = true
      this.error = null
      try {
        const response = await request.post('/user/login', userData)
        this.token = response.data.token
        console.log(response.data)
        localStorage.setItem('token', response.data.token)
        router.push({ name: 'Screen' })
      } catch (error) {
        this.error = error.message
      } finally {
        this.isLoading = false
      }
    },
    async register(userData) {
      this.isLoading = true
      this.error = null
      try {
        const response = await request.post('/user/register', userData)
        this.username = response.username
        this.password = response.password
        this.gender = response.gender
        this.phone = response.phone
        router.push({ name: 'Login' })
      } catch (error) {
        this.error = error.message
      } finally {
        this.isLoading = false
      }
    },
    logout() {
      this.user = null
      this.token = null
    }
  }
})
